package jsyf.oa.service.psi;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.attach.AttachDao;
import jsyf.oa.dao.attach.AttachModuleDao;
import jsyf.oa.dao.psi.GoodsDao;
import jsyf.oa.dao.psi.InventoryDao;
import jsyf.oa.dao.psi.PurchaseDao;
import jsyf.oa.dao.psi.RepoInOutDao;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.attach.AttachModuleEntity;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.entity.psi.InventoryEntity;
import jsyf.oa.entity.psi.RepoEntity;
import jsyf.oa.entity.psi.RepoInOutMainEntity;
import jsyf.oa.entity.system.*;
import jsyf.oa.facade.psi.RepoInOutFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;

/**
 * Created by Maqiuqiu on 2018/10/20.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class RepoInOutService implements RepoInOutFacade {
    @Autowired
    private RepoInOutDao repoinoutDao;
    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private AttachModuleDao attachModuleDao;
    @Autowired
    private AttachDao attachDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CopierDao copierDao;
    @Autowired
    private AuditDao auditDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private AuditHistoryDao auditHistoryDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;

    @Override
    public String save(String jsonData) {
        RepoEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), RepoEntity.class);
        Integer rows;
        if ("0".equals(entity.getMain().getId()) || StringUtils.isBlank(entity.getMain().getId())) {
            rows = repoinoutDao.add(entity.getMain());
            //保存库存表信息
            InventoryEntity inventoryEntity = new InventoryEntity();
            inventoryEntity.setGoodsId(entity.getMain().getGoodsId());
            inventoryEntity.setCount(entity.getMain().getCount());
            inventoryEntity.setAddress(entity.getMain().getInventoryAddress());
            if(entity.getMain().getInOutFlag().equals("1")){
                inventoryEntity.setState("0");
            }else {
                inventoryEntity.setState("2");
            }
            inventoryEntity.setPurchaseId("");
            inventoryEntity.setRepoInOutId(entity.getMain().getId());
            if(entity.getMain().getInOutFlag().equals("1")){
                inventoryEntity.setCreateUserId(entity.getMain().getInUserId());
            }else {
                inventoryEntity.setCreateUserId(entity.getMain().getOutUserId());
            }
            inventoryEntity.setCreateTime(repoinoutDao.getCurrentTime());
            inventoryEntity.setUpdateUserId(entity.getMain().getUpdateUserId());
            inventoryEntity.setUpdateTime(repoinoutDao.getCurrentTime());
            inventoryDao.add(inventoryEntity);
        } else {
            RepoInOutMainEntity repoInOutMainEntity =
                    (RepoInOutMainEntity) repoinoutDao.getIBaseEntityById(entity.getMain().getId());
            repoInOutMainEntity.setDate(entity.getMain().getDate());
            repoInOutMainEntity.setCompanyId(entity.getMain().getCompanyId());
            repoInOutMainEntity.setCompanyName(entity.getMain().getCompanyName());
            repoInOutMainEntity.setDepartId(entity.getMain().getDepartId());
            repoInOutMainEntity.setDepartName(entity.getMain().getDepartName());
            repoInOutMainEntity.setGoodsId(entity.getMain().getGoodsId());
            repoInOutMainEntity.setSourceUrl(entity.getMain().getSourceUrl());
            repoInOutMainEntity.setImageUrl(entity.getMain().getImageUrl());
            repoInOutMainEntity.setCount(entity.getMain().getCount());
            repoInOutMainEntity.setInventoryAddress(entity.getMain().getInventoryAddress());
            repoInOutMainEntity.setTotalPrice(entity.getMain().getTotalPrice());
            repoInOutMainEntity.setKeeperUserId(entity.getMain().getKeeperUserId());
            repoInOutMainEntity.setInUserId(entity.getMain().getInUserId());
            repoInOutMainEntity.setOutUserId(entity.getMain().getOutUserId());
            repoInOutMainEntity.setReceiveUserId(entity.getMain().getReceiveUserId());
            repoInOutMainEntity.setKeeperUserName(entity.getMain().getKeeperUserName());
            repoInOutMainEntity.setInUserName(entity.getMain().getInUserName());
            repoInOutMainEntity.setOutUserName(entity.getMain().getOutUserName());
            repoInOutMainEntity.setReceiveUserName(entity.getMain().getReceiveUserName());
            repoInOutMainEntity.setReceiveDate(entity.getMain().getReceiveDate());
            repoInOutMainEntity.setReceiveUrl(entity.getMain().getReceiveUrl());
            repoInOutMainEntity.setRemark(entity.getMain().getRemark());
            repoInOutMainEntity.setInOutFlag(entity.getMain().getInOutFlag());
            repoInOutMainEntity.setState(entity.getMain().getState());
            repoInOutMainEntity.setAuditFlag(entity.getMain().getAuditFlag());
            repoInOutMainEntity.setCurrentAuditorId(entity.getMain().getCurrentAuditorId());
            repoInOutMainEntity.setCurrentAuditorName(entity.getMain().getCurrentAuditorName());
            repoInOutMainEntity.setCopierReturnReason(entity.getMain().getCopierReturnReason());
            rows = repoinoutDao.update(repoInOutMainEntity);
            //更新库存表信息
            List<InventoryEntity> inventoryEntityList =
                    inventoryDao.getEntityListByCondition("AND GOODS_ID = ? ",new Object[]{entity.getMain().getGoodsId()});
            for (int i = 0; i < inventoryEntityList.size(); i++) {
                InventoryEntity inventoryEntity = inventoryEntityList.get(i);
                inventoryEntity.setGoodsId(entity.getMain().getGoodsId());
                inventoryEntity.setCount(entity.getMain().getCount());
                inventoryEntity.setAddress(entity.getMain().getInventoryAddress());
                if(entity.getMain().getInOutFlag().equals("1")){
                    inventoryEntity.setCreateUserId(entity.getMain().getInUserId());
                }else {
                    inventoryEntity.setCreateUserId(entity.getMain().getOutUserId());
                }
                inventoryEntity.setUpdateUserId(entity.getMain().getUpdateUserId());
                inventoryEntity.setUpdateTime(repoinoutDao.getCurrentTime());
                inventoryDao.update(inventoryEntity);
            }
        }
        String mainId = entity.getMain().getId();
        //保存附件
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{mainId});
        //添加
        List<AttachmentEntity> attachmentEntityList = entity.getAttaches();
        if (attachmentEntityList != null && attachmentEntityList.size() > 0) {
            for (AttachmentEntity attach : attachmentEntityList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(10);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        //保存审核人信息
        if ("0".equals(entity.getMain().getId()) || StringUtils.isBlank(entity.getMain().getId())) {
            //新建-> 直接保存审核人 和抄送人
            saveAuditorsAndCopier(entity.getMain());
        } else {
            //编辑-> 先刪除审核表，重新保存
            delAuditorsAndCopier(entity.getMain().getId());
            saveAuditorsAndCopier(entity.getMain());
        }
        //保存抄送人信息
        copierDao.removeByCondition(" AND MAIN_ID = ? ", new String[]{entity.getMain().getId()});
        List<CopierEntity> copierEntityList = entity.getCopiers();
        for (int i = 0; i < copierEntityList.size(); i++) {
            CopierEntity copierEntity = copierEntityList.get(i);
            copierEntity.setMainId(entity.getMain().getId());
            copierEntity.setModuleName("repoType");
            copierDao.add(copierEntityList.get(i));
        }
        return rows == 0 ? "" : entity.getMain().getId();
    }

    private void saveAuditorsAndCopier(RepoInOutMainEntity main) {
        List<AuditEntity> auditList = new ArrayList<>();
        List<CopierEntity> copierList = new ArrayList<>();
        //查询总经理
        String allParentStr = checkDao.getParentByUserId(main.getInUserId(), true);
        String[] allParentArr = allParentStr.split(",");
        boolean hasZongJingLi = false;
        //按主职位查
        for (int i = 0; i < allParentArr.length; i++) {
            List<JSONObject> objectList =
                    userDao.getViewByUserId(" AND id = ? AND main=1 AND jobState !=1",
                            new Object[]{allParentArr[i].substring(1, allParentArr[i].length() - 1)});
            if (objectList != null && objectList.size() > 0) {
                JSONObject jsonObject = objectList.get(0);
                if (jsonObject.getString("roleName").equals("总经理")) {
                    AuditEntity firstAuditor = new AuditEntity();
                    firstAuditor.setAuditorId(jsonObject.getString("id"));
                    firstAuditor.setAuditorName(jsonObject.getString("name"));
                    firstAuditor.setRoleName((jsonObject.getString("roleName")));
                    firstAuditor.setAuditFlag(-1);
                    firstAuditor.setAuditSort(0);
                    firstAuditor.setMainId(main.getId());

                    auditList.add(firstAuditor);
                    hasZongJingLi = true;
                }
//                if (jsonObject.getString("roleName").equals("总经理")) {
//                    CopierEntity copierEntity = new CopierEntity();
//                    copierEntity.setCopierId(jsonObject.getString("id"));
//                    copierEntity.setCopierName(jsonObject.getString("name"));
//                    copierEntity.setMainId(main.getId());
//
//                    copierList.add(copierEntity);
//                }
            }
        }
        //按兼职位查
        if (hasZongJingLi) {

        } else {
            for (int i = 0; i < allParentArr.length; i++) {
                List<JSONObject> objectList =
                        userDao.getViewByUserId(" AND id = ? AND main=0 AND jobState !=1",
                                new Object[]{allParentArr[i].substring(1, allParentArr[i].length() - 1)});
                if (objectList != null && objectList.size() > 0) {
                    for (int j = 0; j < objectList.size(); j++) {
                        JSONObject jsonObject = objectList.get(j);
                        if (jsonObject.getString("roleName").equals("总经理") && !hasZongJingLi) {
                            AuditEntity firstAuditor = new AuditEntity();
                            firstAuditor.setAuditorId(jsonObject.getString("id"));
                            firstAuditor.setAuditorName(jsonObject.getString("name"));
                            firstAuditor.setRoleName((jsonObject.getString("roleName")));
                            firstAuditor.setAuditFlag(-1);
                            firstAuditor.setAuditSort(0);
                            firstAuditor.setMainId(main.getId());

                            auditList.add(firstAuditor);
                            hasZongJingLi = true;
                        }
                    }
                }
            }
        }
        AuditEntity lastAuditor = new AuditEntity();
        lastAuditor.setAuditorId("201711271733404C9DA1461F2421F828");
        lastAuditor.setAuditorName("曹国玉");
        lastAuditor.setRoleName("后台管理");
        lastAuditor.setAuditFlag(-1);
        lastAuditor.setAuditSort(1);
        lastAuditor.setMainId(main.getId());


        auditList.add(lastAuditor);
        //去除重复的审核人
        List<AuditEntity> tempList = new ArrayList<>();
        String idStr = "";
        for (int i = 0; i < auditList.size(); i++) {
            if (!idStr.contains(auditList.get(i).getAuditorId())) {
                idStr += auditList.get(i).getAuditorId() + ",";
                tempList.add(auditList.get(i));
            }
        }
        auditList = tempList;
        //去除重复的抄送人
        List<CopierEntity> temp2List = new ArrayList<>();
        String id2Str = "";
        for (int i = 0; i < copierList.size(); i++) {
            if (!id2Str.contains(copierList.get(i).getCopierId())) {
                id2Str += copierList.get(i).getCopierId() + ",";
                temp2List.add(copierList.get(i));
            }
        }
        copierList = temp2List;
        for (int i = 0; i < copierList.size(); i++) {
            copierDao.add(copierList.get(i));
        }
        //排序
        Collections.sort(auditList, new Comparator<AuditEntity>() {

            @Override
            public int compare(AuditEntity o1, AuditEntity o2) {
                return o1.getAuditSort().compareTo(o2.getAuditSort());// 按照sortNo升序
            }
        });
        for (int i = 0; i < auditList.size(); i++) {
            auditDao.add(auditList.get(i));
        }
        //设置当前审核人
        setCurrentAuditor(main, auditList.get(0));
    }

    //删除审核人和抄送人
    private void delAuditorsAndCopier(String mainId) {
        auditDao.removeByCondition(" AND MAIN_ID = ? ", new String[]{mainId});
        copierDao.removeByCondition(" AND MAIN_ID = ? ", new String[]{mainId});
    }

    //更新主表 审核人和审核表的第一审核人
    private void setCurrentAuditor(RepoInOutMainEntity main, AuditEntity currentAuditor) {
        List<JSONObject> jsonObjectList = new ArrayList<>();
        main.setCurrentAuditorId(currentAuditor.getAuditorId());
        main.setCurrentAuditorName(currentAuditor.getAuditorName());
        //currentAuditor.setAuditFlag(0);
        currentAuditor.setAuditFlag(Integer.valueOf(main.getAuditFlag()));
        repoinoutDao.update(main);
        auditDao.update(currentAuditor);

//        //企业号:给第一审核人发送消息
//        JSONObject msgObject = new JSONObject();
//        msgObject.put("userIds", main.getCurrentAuditorId());
//        msgObject.put("content", String.format(TRUCK_AUDIT_AUDIT,
//                main.getCurrentAuditorName(),
//                main.getRegionalManagerName(),
//                DateUtils.parse(main.getUpdateTime(), "yyyy-MM-dd HH:mm")
//        ));
//        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
//
//        //保存消息到消息表t_sys_message
//        MessageEntity messageEntity = new MessageEntity();
//        messageEntity.setCreateUserId(main.getRegionalManagerId());
//        messageEntity.setCreateTime(messageDao.getCurrentTime());
//        messageEntity.setContent(String.format(TRUCK_AUDIT_ONE,main.getRegionalManagerName()));
//        messageEntity.setMessageType(1);
//        messageEntity.setMainId(main.getId());
//        messageEntity.setDelFlag(0);
//        messageEntity.setOpenUrl("/page/reportForm/salesForecastReport/thursdayTrackList.html");
//        messageEntity.setOpenTitle(String.format(TRUCK_AUDIT_ONE,main.getRegionalManagerName()));
//        messageDao.add(messageEntity);
//
//        //保存第一审核人信息到消息收件人表t_sys_message_receiver
//        MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
//        messageReceiverEntity.setMessageId(messageEntity.getId());
//        messageReceiverEntity.setUserId(main.getRegionalManagerId());
//        messageReceiverEntity.setUserType(0);
//        messageReceiverEntity.setReadFlag(0);
//        messageReceiverDao.add(messageReceiverEntity);
//
//        //发消息
//        jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
    }

    @Override
    public Boolean delById(String id) {
        return repoinoutDao.delById(id) > 0;
    }

    @Override
    public Boolean removeById(String id) {
        return repoinoutDao.removeById(id) > 0;
    }

    @Override
    public JSONObject getRepoById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject results = new JSONObject();
        String id = jsonParams.getString("id");
        JSONObject result = repoinoutDao.getJSONById(id);
        JSONObject goodsInfo = goodsDao.getJSONById(result.getString("goodsId"));
        result.put("goodsName",goodsInfo.getString("name"));
        result.put("goodsSpec",goodsInfo.getString("spec"));
        result.put("goodsUnit",goodsInfo.getString("unit"));
        result.put("goodsUnitPrice",goodsInfo.getString("unitPrice"));
        List<JSONObject> auditors =
                auditDao.getJSONListByCondition(" and MAIN_ID = ? ORDER BY AUDIT_SORT", new Object[]{id});
        List<JSONObject> copiers =
                copierDao.getJSONListByCondition(" and MAIN_ID = ?", new Object[]{id});
        List<JSONObject> auditHistorys =
                auditHistoryDao.getJSONListByCondition(" AND MAIN_ID = ? AND AUDIT_FLAG=2 ORDER BY AUDIT_TIME DESC", new Object[]{id});
        List<JSONObject> repoHistory =
                repoinoutDao.getJSONListByCondition("AND GOODS_ID = ? AND AUDIT_FLAG = '1' AND IN_OUT_FLAG = '0' ORDER BY DATE DESC ",new Object[]{result.getString("goodsId")});
        List<AttachModuleEntity> attachModuleEntities =
                attachModuleDao.getEntityListByCondition("AND MODULE_ID = ? ",new Object[]{id});
        for (int i = 0; i < repoHistory.size(); i++) {
            JSONObject object = repoHistory.get(i);
            for (int j = 0; j < attachModuleEntities.size(); j++) {
                AttachModuleEntity entity = attachModuleEntities.get(j);
                JSONObject jsonObject = attachDao.getJSONById(entity.getAttachId());
                String url = jsonObject.getString("url");
                String name = jsonObject.getString("name");
                object.put("url",url);
                object.put("name",name);
            }
        }
        results.put("main", result);
        results.put("auditors", auditors);
        results.put("copiers", copiers);
        results.put("auditHistorys", auditHistorys);
        results.put("repoHistory", repoHistory);
        return results;
    }

    @Override
    public JSONObject getOutRepoList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String key = jsonParams.getString("key");
        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        //传参
        StringBuffer condition = new StringBuffer();
        if (!StringUtils.isBlank(key)) {
            condition.append(" AND (t_psi_goods.`NAME` LIKE '%" + key + "%' " +
                    "OR t_psi_inventory.ADDRESS LIKE '%" + key + "%')");
        }
        condition.append(" AND t_psi_repo_in_out.IN_OUT_FLAG = '0'   ");
        condition.append(" ORDER BY t_psi_inventory.CREATE_TIME DESC   ");
        //查询list
        List<JSONObject> records = inventoryDao.getInventoryList(userId,condition.toString(),requestPage,pageSize);
        //查询总数
        int recordCount = inventoryDao.getInventoryList(userId,condition.toString(), 1, Integer.MAX_VALUE).size();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        //子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject applyAudit(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        JSONObject result = new JSONObject();
        String id = jsonPalams.getString("id");
        String auditFlag = jsonPalams.getString("auditFlag");//审核状态
        String userId = jsonPalams.getString("userId");//当前审核人ID
        String userName = jsonPalams.getString("userName");//当前审核人NAME
        String roleName = jsonPalams.getString("roleName");//当前审核人ROLENAME
        String advise = jsonPalams.getString("advise");//意见
        RepoInOutMainEntity repoInOutMainEntity = (RepoInOutMainEntity) repoinoutDao.getIBaseEntityById(id);
        //添加历史审核记录
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setMainId(id);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditorId(userId);
        auditHistoryEntity.setAuditorName(userName);
        auditHistoryEntity.setAuditTime(auditHistoryDao.getCurrentTime());
        auditHistoryEntity.setAuditType(8);
        auditHistoryDao.add(auditHistoryEntity);
        //更新当前审核人的--审核表记录
        List<AuditEntity> auditEntityList = (List<AuditEntity>) (Object)
                auditDao.getIBaseEntityByCondition(" and MAIN_ID = ? and AUDITOR_ID = ? ", new Object[]{id, userId});
        if (null != auditEntityList && auditEntityList.size() > 0) {
            AuditEntity auditEntity = auditEntityList.get(0);
            auditEntity.setAuditFlag(Integer.parseInt(auditFlag));
            auditEntity.setAuditAdvise(advise);
            auditEntity.setAuditTime(auditDao.getCurrentTime());
            auditEntity.setAuditorName(userName);
            auditEntity.setRoleName(roleName);
            auditDao.update(auditEntity);
        }
        //修改主表审核信息----->>>-1未到轮次/初始状态>>>0当前等待审核>>>1通过>>>2驳回
        List<AuditEntity> auditList =  (List<AuditEntity>) (Object)
                auditDao.getIBaseEntityByCondition("and MAIN_ID = ?  order by audit_sort", new Object[]{id});
        for (int i = 0; i < auditList.size(); i++) {
            AuditEntity audit = auditList.get(i);
            if (audit.getAuditorId().equals(userId)) {
                //如果是驳回，修改主表状态为驳回->2
                if (auditFlag.equals("2")) {
                    repoInOutMainEntity.setAuditFlag("2");
                    repoinoutDao.update(repoInOutMainEntity);

                    //企业号:审核驳回，发消息通知申请人
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", repoInOutMainEntity.getInUserId());
                    //msgObject.put("userIds", "2017121820434803834AA7E354A82ABB");
                    msgObject.put("content", String.format(TRUCK_AUDIT_REJECT,
                            repoInOutMainEntity.getInUserName(),
                            audit.getAuditAdvise(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    //审核驳回，发送消息给申请人，保存消息到消息表t_sys_message
                    MessageEntity messageCreateEntity = new MessageEntity();
                    messageCreateEntity.setCreateUserId(repoInOutMainEntity.getOutUserId());
                    messageCreateEntity.setCreateTime(repoinoutDao.getCurrentTime());
                    messageCreateEntity.setContent(String.format(TRUCK_AUDIT_REJECT,
                            repoInOutMainEntity.getOutUserId(),
                            audit.getAuditAdvise(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    messageCreateEntity.setMessageType(0);
                    messageCreateEntity.setMainId(id);
                    messageCreateEntity.setDelFlag(0);
                    messageCreateEntity.setOpenUrl("/page/psi/out_repo.html?id="
                            + repoInOutMainEntity.getId() + "&pageType=look");
                    messageCreateEntity.setOpenTitle(String.format(REPO_AUDIT_THREE, audit.getAuditorName()));
                    messageDao.add(messageCreateEntity);

                    //审核驳回，发送消息给申请人,保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageCreateReceiverEntity = new MessageReceiverEntity();
                    messageCreateReceiverEntity.setMessageId(messageCreateEntity.getId());
                    messageCreateReceiverEntity.setUserId(repoInOutMainEntity.getOutUserId());
                    messageCreateReceiverEntity.setUserType(2);
                    messageCreateReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageCreateReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(messageCreateEntity, messageCreateReceiverEntity));
                    break;
                }
                //如果是最后一个人审核通过，标记主表状态为通过->1
                if (auditList.size() - 1 == i) {
                    repoInOutMainEntity.setAuditFlag("1");
                    repoInOutMainEntity.setState("1");
                    repoinoutDao.update(repoInOutMainEntity);
                    //企业号: 最后一个审核通过,发送消息给申请人
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", repoInOutMainEntity.getInUserId());
                    //msgObject.put("userIds", "2017121820434803834AA7E354A82ABB");
                    msgObject.put("content", String.format(TRUCK_AUDIT_PASS,
                            repoInOutMainEntity.getInUserName(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    //审核通过，发送消息给申请人，保存消息到消息表t_sys_message
                    MessageEntity msgAuditEntity = new MessageEntity();
                    msgAuditEntity.setCreateUserId(repoInOutMainEntity.getOutUserId());
                    msgAuditEntity.setCreateTime(repoinoutDao.getCurrentTime());
                    msgAuditEntity.setContent(String.format(TRUCK_AUDIT_PASS,
                            repoInOutMainEntity.getOutUserId(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    msgAuditEntity.setMessageType(0);
                    msgAuditEntity.setMainId(id);
                    msgAuditEntity.setDelFlag(0);
                    msgAuditEntity.setOpenUrl("/page/psi/out_repo.html?id="
                            + repoInOutMainEntity.getId() + "&pageType=look");
                    msgAuditEntity.setOpenTitle(String.format(REPO_AUDIT_TWO,  audit.getAuditorName()));
                    messageDao.add(msgAuditEntity);

                    //审核通过，发送消息给申请人，保存消息到表t_sys_message_receiver
                    MessageReceiverEntity msgReceiverEntity = new MessageReceiverEntity();
                    msgReceiverEntity.setMessageId(msgAuditEntity.getId());
                    msgReceiverEntity.setUserId(repoInOutMainEntity.getOutUserId());
                    msgReceiverEntity.setUserType(2);
                    msgReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(msgReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(msgAuditEntity, msgReceiverEntity));
                }
            } else {
                //下一位审核人才进入，修改审核表状态和主表审核人信息
                if (audit.getAuditFlag().toString().equals("-1")) {
                    audit.setAuditFlag(0);
                    auditDao.update(audit);
                    repoInOutMainEntity.setCurrentAuditorName(audit.getAuditorName());
                    repoInOutMainEntity.setCurrentAuditorId(audit.getAuditorId());
                    repoInOutMainEntity.setAuditFlag(audit.getAuditFlag().toString());
                    repoinoutDao.update(repoInOutMainEntity);
                    break;
                }
            }
        }
        //发消息
        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    private JSONObject getMessage(MessageEntity messageEntity, MessageReceiverEntity messageReceiverEntity) {
        String userId = messageEntity.getCreateUserId();
        UserEntity userEntity = userDao.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", messageEntity.getId());
        jsonObject.put("createUserId", userId);
        jsonObject.put("createUserName", userEntity.getName());
        jsonObject.put("createTime", messageEntity.getCreateTime());
        jsonObject.put("content", messageEntity.getContent());
        jsonObject.put("mainId", messageEntity.getMainId());
        jsonObject.put("delFlag", messageEntity.getDelFlag());
        jsonObject.put("openTitle", messageEntity.getOpenTitle());
        jsonObject.put("openUrl", messageEntity.getOpenUrl());
        jsonObject.put("messageType", messageEntity.getMessageType());
        jsonObject.put("receiverId", messageReceiverEntity.getId());
        jsonObject.put("receiverUserId", messageReceiverEntity.getUserId());
        jsonObject.put("receiverUserType", messageReceiverEntity.getUserType());
        jsonObject.put("receiverReadFlag", messageReceiverEntity.getReadFlag());
        return jsonObject;
    }
}
